<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>12_生成器-生成器代替迭代器</title>
</head>
<body>

  <script>
    // 1. 对之前的代码进行重构(生成器)
    const names = ['张三', '李四', '王五'];
    
    function* createArrayIterator(arr) {
      for (let i = 0; i < arr.length; i++) {
        yield arr[i]; // yield关键字，每次迭代时，返回一个值，并且暂停函数的执行
      }
    }

    const namesIterator = createArrayIterator(names);
    console.log(namesIterator.next());
    console.log(namesIterator.next());
    console.log(namesIterator.next());
    console.log(namesIterator.next());

    // 2. 生成器函数, 某个访问[3, 6)
    function* createRangeGenerator(start, end) {
      for (let i = start; i < end; i++) {
        yield i
      }
    }

    const rangeGen = createRangeGenerator(3, 6)
    console.log(rangeGen.next())
    console.log(rangeGen.next())
    console.log(rangeGen.next())
    console.log(rangeGen.next())
    console.log(rangeGen.next())
    console.log(rangeGen.next())
    console.log(rangeGen.next())



  </script>
  
</body>
</html>